package com.emm.yixun.website.controller.system;
//框架包
import java.util.ArrayList;
import java.util.Date;

import com.emm.yixun.website.constant.EhcacheConstant;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.model.Department;
import com.emm.yixun.common.model.Role;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.DepartmentDto;
import com.emm.yixun.common.model.dto.RootClass;
//变化的引用
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.page.Page;
//common
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.DateStyle;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.common.utils.PasswordUtil;
import com.emm.yixun.system.service.DepartmentServiceFacade;
import com.emm.yixun.system.service.RoleServiceFacade;
import com.emm.yixun.system.service.SMSMessageFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.system.service.UserTokenServiceFacade;
//website
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.utils.SMSContextUtils;
import com.emm.yixun.website.vo.system.UserVo;
@Controller
@RequestMapping("/system/user/")
public class UserController extends BaseController<User>{
	@Autowired
	private UserServiceFacade userServiceFacade;
	
	@Autowired
	private DepartmentServiceFacade departmentServiceFacade;
	
	@Autowired
	private RoleServiceFacade roleServiceFacade;
	
	@Autowired
	private UserTokenServiceFacade userTokenServiceFacade;
	
	@Autowired
	private SMSMessageFacade smsMessageFacade;
	
	@Value("${sms.passwordMsg}")
	private String context;
	
	@RequestMapping(value="index")
	public String index(ModelMap map){
		if(doSecurityIntercept(Const.RESOURCES_TYPE_MENU)){
			//查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));		
			return "/system/user/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	//新增返回实体对象
	@RequestMapping(value="add", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  add(UserDto dto,String birthdayStr,String entryTimeStr){
    	AjaxRes ar=getAjaxRes();
    	
    	/*
    	 *1.判断权限 
    	 *2.调用新增接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:user:add"))){
        	try {
        		User user=ShiroUtil.getCurrentUser();
        		dto.setMerchantId(user.getMerchantId());
        		dto.setCreateUserId(user.getId());
        		dto.setIsAdmin("0");
        		dto.setDelFlag("0");
        		dto.setSkin("skin-1");
        		dto.setUpdateUserId(user.getId());
        		dto.setUpdateTime(new Date());
        		dto.setUserPassword(PasswordUtil.md5Hex(dto.getUserPassword()));
        		dto.setBirthday(DateUtils.StringToDate(birthdayStr, DateStyle.YYYY_MM_DD));
        		dto.setEntryTime(DateUtils.StringToDate(entryTimeStr, DateStyle.YYYY_MM_DD));
        		Response<Department> departmentResponse=departmentServiceFacade.findById(dto.getUserDepartmentId());
        		if(departmentResponse.isSuccess() && null!=departmentResponse.getEntity()){
        			dto.setUserDepartmentPath(departmentResponse.getEntity().getPermissionCode());
        		}
				Response<UserDto> response=userServiceFacade.save(dto);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				}else{
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
    	}
    	return ar;
    }
	//查看
	@RequestMapping(value="view", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  view(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:user:view"))){
        	try {
				Response<User> response=userServiceFacade.findById(id);
				if(response.isSuccess()){
					UserVo uv=new UserVo();
            		uv=BeanUtil.convert2T(uv, response.getEntity());
            		uv.setBirthdayStr(DateUtils.DateToString(uv.getBirthday(), DateStyle.YYYY_MM_DD));
            		uv.setEntryTimeStr(DateUtils.DateToString(uv.getEntryTime(), DateStyle.YYYY_MM_DD));
					ar.setSucceed(uv);
				}else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	
	//修改
	@RequestMapping(value="edit", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  edit(UserDto dto,String birthdayStr,String entryTimeStr){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:user:edit"))){
        	try {
        		//20180412 增加修改人ID
        		User user = ShiroUtil.getCurrentUser();
        		dto.setUpdateUserId(user.getId());
        		
        		Response<User> userEntity = userServiceFacade.findById(dto.getId());
        		dto.setBirthday(DateUtils.StringToDate(birthdayStr, DateStyle.YYYY_MM_DD));
        		dto.setEntryTime(DateUtils.StringToDate(entryTimeStr, DateStyle.YYYY_MM_DD));
        		dto.setUserDepartmentId(null);
        		Response<Integer> response=userServiceFacade.updateByPrimaryKey(dto,true,true);
				if(response.isSuccess()){
					//如果两个角色ID不一样，则需写入重新登陆标示，app账号需要重新登陆
	        		if(!String.valueOf(userEntity.getEntity().getRoleId()).equals(String.valueOf(dto.getRoleId())) && String.valueOf(userEntity.getEntity().getId()).equals(String.valueOf(dto.getId()))){
						user.setRoleId(dto.getRoleId());
	        			Subject currentUser = SecurityUtils.getSubject();
						Session session = currentUser.getSession();
						session.setAttribute(Const.SESSION_USER, user);

	        			//默认管理员
						String roleIdStr = EhcacheConstant.ADMIN_ROLE_ID;
						String newRoleIdStr = EhcacheConstant.ADMIN_ROLE_ID;
						//系统管理员角色ID为null,当roleId不为null时，则认为是普通用户
						if (!user.getIsAdmin().equals("1")){
							roleIdStr = String.valueOf(userEntity.getEntity().getRoleId());
							newRoleIdStr = String.valueOf(dto.getRoleId());
						}
	        			String cacheKey=String.format(EhcacheConstant.MERCHANT_ROLE_BUTTON_CACHE_KEY, String.valueOf(user.getMerchantId()), roleIdStr);
						String newCacheKey=String.format(EhcacheConstant.MERCHANT_ROLE_BUTTON_CACHE_KEY, String.valueOf(user.getMerchantId()), newRoleIdStr);
						cacheUtils.remove(EhcacheConstant.ACTIVE_SESSIONS_CACHE, cacheKey);
						cacheUtils.remove(EhcacheConstant.ACTIVE_SESSIONS_CACHE, newCacheKey);
						userTokenServiceFacade.addRoleAndUserLogin(String.valueOf(dto.getRoleId()), String.valueOf(dto.getId()));
	        		}
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				}else{
					ar.setFailMsg(response.getResultMessage());
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	
	//初始化密码
	@RequestMapping(value="updPassWord", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes updPassWord(UserDto dto){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用修改接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:user:updPassWord"))){
        	try {
        		//发送短信
        		String initPassWord = SMSContextUtils.initPassWord();
        		Response<User> responseUser = userServiceFacade.findById(dto.getId());
        		if(responseUser.isSuccess()&&responseUser.getEntity()!=null){
        			User user = responseUser.getEntity();
        			String[] value = new String[]{user.getUserName(),initPassWord};
        			boolean flag = smsMessageFacade.sendMobileMsg(user.getUserPhone(), SMSContextUtils.repContext(context, value));
        			if(flag){
        				dto.setUserPassword(PasswordUtil.md5Hex(initPassWord));
                		Response<Integer> response=userServiceFacade.updateByPrimaryKey(dto,false,true);
        				if(response.isSuccess()){
        					ar.setSucceedMsg(Const.START_SUCMSG);
        				}else{
        					ar.setFailMsg(response.getResultMessage());
        				}
        			}else{
        				ar.setFailMsg(Const.UPDATE_FAIL);
        			}
        		}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
    	}
    	return ar;
    }
	

	
	//删除
	@RequestMapping(value="delete", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  delete(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:user:delete"))){
        	try {
        		Response<Integer> response=userServiceFacade.deleteByPrimaryKey(id);
				if(response.isSuccess()){
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				}else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
    	}
    	return ar;
    }

	//分页查询
	@RequestMapping(value="list", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  list(UserDto dto,Integer pageSize,Integer pageNum){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用分页查询接口
    	 *3.返回信息
    	*/
        if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:user:list"))){
        	try {
        		if(null!=dto.getRoleId() && dto.getRoleId()==-1){
        			dto.setRoleId(null);
        		}
        		if(StringUtils.isNoneBlank(dto.getUserName())){
        			dto.setUserName(dto.getUserName().trim());
        		}
        		User user = ShiroUtil.getCurrentUser();
        		dto.setPermissionUserId(user.getId());
        		
        		//机构会员数据权限资源缓存
        		String resourcesCode = ShiroUtil.getDataPermissionResources(dto.getResourcesName());
        		if(null == dto.getResourcesCode() || "".equals(dto.getResourcesCode())){
        			dto.setResourcesCode(resourcesCode);
        		}else if("".equals(resourcesCode)){
        			ShiroUtil.setDataPermissionResources(dto.getResourcesName(), dto.getResourcesCode());
        		}
        		dto.setMerchantId(user.getMerchantId());
        		
        		//会员关联机构,使用机构表的别名
        		dto.setPrefix("dept");
        		if(dto.getUserDepartmentId()!=null){
        		    Response<Department> responseDepResponse=   departmentServiceFacade.findById(dto.getUserDepartmentId());
        		    if(responseDepResponse.getEntity()==null){
        			dto.setUserDepartmentId(null);
        		    }
        		}
        		Page<User> response=userServiceFacade.findPageByDto(dto, PageUtil.begin(pageNum, pageSize),pageSize);
        		if(response.getSuccess()){
                	if(null==response.getRows())response.setRows(new ArrayList<User>());
                	response.setPageNumber(pageNum);
                	ArrayList<UserVo> list=new ArrayList<UserVo>();
                	for(User u : response.getRows()){
                		UserVo uv=new UserVo();
                		uv=BeanUtil.convert2T(uv, u);
                		//部门
                		Response<Department> deptResponse=departmentServiceFacade.findById(u.getUserDepartmentId());
                		if(deptResponse.isSuccess()){
                			uv.setDeptName(deptResponse.getEntity().getDepartmentName());
                		}
                		//查询角色
                		Response<Role> roleResponse=roleServiceFacade.findById(u.getRoleId());
                		if(roleResponse.isSuccess()){
                			uv.setRoleName(roleResponse.getEntity().getRoleName());
                		}
                		list.add(uv);
                	}
                	Page<UserVo> resultPage = new Page<UserVo>(response.getTotal(), list); 
                	resultPage.setPageSize(pageSize);
                	resultPage.setPageNumber(pageNum);
                	ar.setSucceed(resultPage);
                }else{
                	ar.setFailMsg(Const.DATA_FAIL);
                }
			} catch (Exception e) {
				logger.error(e.toString(),e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
    	}
    	return ar;
    }
	//查询部门员工
	@RequestMapping(value="findUserByDeptId", method=RequestMethod.POST)
	@ResponseBody
	public AjaxRes findUserByDeptId(String deptId){
		AjaxRes ar=getAjaxRes();
		try {
			User user=ShiroUtil.getCurrentUser();
			UserDto dto=new UserDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setUserDepartmentId(Long.valueOf(deptId));
			ResponseList<User> responseList=userServiceFacade.findByDto(dto);
			if(responseList.isSuccess() && null!=responseList.getEntity()){
				ar.setSucceed(responseList.getEntity());
			}else{
				ar.setSucceed(new ArrayList<User>());
			}
		} catch (Exception e) {
			logger.error(e.toString(),e);
			ar.setSucceed(new ArrayList<User>());
		}
		return ar;
	}
	
	//查询部门员工
	@RequestMapping(value="findRoleUser", method=RequestMethod.POST)
	@ResponseBody
	public AjaxRes findRoleUser(Long roleId){
		AjaxRes ar=getAjaxRes();
		try {
			User user=ShiroUtil.getCurrentUser();
			UserDto dto=new UserDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setRoleId(roleId);
			dto.setIsAdmin("0");
			ResponseList<User> responseList=userServiceFacade.findByDto(dto);
			if(responseList.isSuccess() && null!=responseList.getEntity()){
				ar.setSucceed(responseList.getEntity());
			}else{
				ar.setSucceed(new ArrayList<User>());
			}
		} catch (Exception e) {
			logger.error(e.toString(),e);
			ar.setSucceed(new ArrayList<User>());
		}
		return ar;
	}
	
	@RequestMapping(value="findUserById", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  findUserById(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
    	try {
			Response<User> response=userServiceFacade.findById(id);
			if(response.isSuccess()){
				UserVo uv=new UserVo();
        		uv=BeanUtil.convert2T(uv, response.getEntity());
        		uv.setBirthdayStr(DateUtils.DateToString(uv.getBirthday(), DateStyle.YYYY_MM_DD));
        		uv.setEntryTimeStr(DateUtils.DateToString(uv.getEntryTime(), DateStyle.YYYY_MM_DD));
				ar.setSucceed(uv);
			}else {
				ar.setFailMsg(Const.DATA_FAIL);
			}
		} catch (Exception e) {
			logger.error(e.toString(),e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
    	return ar;
    }
	
	@RequestMapping(value="findUserPhone", method=RequestMethod.POST)
	@ResponseBody
    public AjaxRes  findUserPhone(Long id){
    	AjaxRes ar=getAjaxRes();
    	/*
    	 *1.判断权限 
    	 *2.调用查看接口
    	 *3.返回信息
    	*/
    	try {
    		
    		User user=ShiroUtil.getCurrentUser();
    		Response<User> response=userServiceFacade.findById(user.getId());
    		if(response.isSuccess()){
    			user=response.getEntity();
    		}
    		String userPhone=user.getUserPhone();
    		JSONArray phoneList=new JSONArray();
    		JSONObject firstPhone=new JSONObject();
    		firstPhone.put("type", "1");
    		firstPhone.put("phone", userPhone);
    		phoneList.add(firstPhone);
    		String userLandlines=user.getUserLandlines();
    		if(StringUtils.isNotBlank(userLandlines)){
    			JSONArray phoneArray=JSON.parseArray(userLandlines);
    			for(int i=0;i<phoneArray.size();i++){
    				JSONObject row=phoneArray.getJSONObject(i);
    				phoneList.add(row);
    			}
    			
    		}
    		ar.setSucceed(phoneList.toJSONString());
		} catch (Exception e) {
			logger.error(e.toString(),e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
    	return ar;
    }
	
	//查询员工部门
	@RequestMapping(value="findUserDept")
	@ResponseBody
	public RootClass findUserDept(){
		User user=ShiroUtil.getCurrentUser();
		DepartmentDto deptDto = new DepartmentDto();
		deptDto.setId(user.getUserDepartmentId());
		deptDto.setDataPermission(" permission_code like '"+user.getUserDepartmentPath()+"%'");
		ResponseList<Department> responseList = departmentServiceFacade.findByDto(deptDto);
		RootClass root = new RootClass();
		root.setRoot(responseList.getEntity());
		return root;
	}
	
	//查询部门员工,通过Code去查询,可以支持like模糊匹配
	@RequestMapping(value="findUserByDeptPath")
	@ResponseBody
	public RootClass findUserByDeptPath(String deptPath){
		User user=ShiroUtil.getCurrentUser();
		UserDto dto=new UserDto();
		dto.setMerchantId(user.getMerchantId());
		dto.setUserDepartmentPath(deptPath);
		ResponseList<User> responseList=userServiceFacade.findByDto(dto);
		RootClass root = new RootClass();
		root.setRoot(responseList.getEntity());
		return root;
	}
	
	//查询所有部门
	@RequestMapping(value="findAllDept")
	@ResponseBody
	public AjaxRes findAllDept(){
		AjaxRes ar=getAjaxRes();
		User user=ShiroUtil.getCurrentUser();
		DepartmentDto deptDto = new DepartmentDto();
		deptDto.setMerchantId(user.getMerchantId());
		ResponseList<Department> responseList = departmentServiceFacade.findByDto(deptDto);
		ar.setSucceed(responseList.getEntity());
		return ar;
	}
	
}
